"""
支付接口实现思路：

支付平台下发访问密钥（AccessKey）。在调用API时需要使用AccessKey完成身份验证。
此密钥由商城开发人员获得

使用时此密钥会与当前时间戳进行拼接(或拼接所有参数)，使用加密算法后向api发送请求以及加密的时间戳，后台使用相同的加密算法进行解密，若一致才可返回响应。

安全保障原理：
密钥只有后端配置知道，与时间戳拼接加密

请求思路：
商城方发起请求，重定向至支付平台，平台验签返回相应结果

支付记录（paylog）：
账户，时间，使用人，金额大小，需要商城方上传用户id,

支付发生在商城后台，由响应结果判断支付是否成功

一旦成功转跳至成功界面，界面设置倒计时转跳至商城页面和点击转跳页面


"""


from WebFrame.wsgi import app,hash, redirect
from WebFrame.ORM import select,insert,update
import json
import time
BANK = ['id', 'account_num', 'create_time']

import requests

USER = ['id', 'username', 'password', 'truename', 'birthday',
        'phone', 'address', 'zipcode', 'balance', 'create_time']
AccessKey="1asasasasfasfasfaf"

def verify(time_stamp,user_id,token,amount):
    now=int(time.time())
    if now-int(time_stamp)>30:#超过30秒报错
            message='支付超时'
            return message
    sql = f'SELECT * FROM `user` where id=%s'
    arg=(user_id,)
    user = select(sql,arg, USER)
    if not user:
        message='非法用户'
        return message
    server_token=hash(AccessKey+time_stamp+amount+user_id)
    if token!=server_token:
        message='验签失败'
        return message
    return False

def send2mall(user_id,amount):
    url='http://127.0.0.1:8000/recharge1/'
    try:
        data={"user_id":user_id,'amount':amount}
        print(data)
        r = requests.get(url, params=data)
        print(time.localtime())
        r_json=json.loads(r.text)
        # print(r_json,type(r_json))
        
        if r_json['state']=='ok':
            return True
        else:
            return False
    except Exception as e:
        print(e)
        pass
    return False




@app.route('/pay/')
def pay(request):
    if request.get('REQUEST_METHOD') == 'GET':
        message=''
        data=app.args
        token=data.get('token')
        time_stamp=data.get('time_stamp')
        user_id=data.get('user_id')
        amount=data.get('amount')
        message=verify(time_stamp,user_id,token,amount)
        if not message:
            message=''
    else:
        data=app.form
        # print(data)
        token=data.getvalue('token')
        time_stamp=data.getvalue('time_stamp')
        amount=data.getvalue('amount')
        user_id=data.getvalue('user_id')
        account_num=data.getvalue('account_num')
        # print(time_stamp,user_id,token,amount)
        
        if not (token and time_stamp and amount and user_id and account_num):
            return redirect('/error/')
        # print(time_stamp,user_id,token,amount)
        # print(time.localtime())
        message=verify(time_stamp,user_id,token,amount)
        if not message:
            message=''
            sql = 'SELECT * FROM `bank` where account_num=%s'
            arg=(account_num,)
            bank = select(sql,arg, BANK)
            # print(222,time.localtime())
            if  not bank:
                message='账户不存在，检查后重试'
            print(1111,time.localtime())
            if send2mall(user_id,amount):
                # print(time.localtime())
                message='充值成功'
                sql = f"INSERT INTO `logs` (`account_num`, `user_id`, `amount`, `time_stamp`) VALUES ('{account_num}', '{user_id}', '{amount}', '{time_stamp}')"
                insert(sql)
                return app.render(request, 'success.html', {'amount': amount, 'message': message})

            else:
                message='充值失败'

    return app.render(request, 'recharge.html', {'amount': amount, 'message': message,'token':token,'user_id':user_id,'time_stamp':time_stamp})